<?php

/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-01-20
 * 版    本：1.0.0
 * 功能说明：用户控制器。
 *
 * */

namespace Qwadmin\Controller;

use Common\Controller\OdooApiController;
use Common\Upload;

//use Common\Controller\openerp;

class GoodsController extends ComController {
    /*
     * 商品列表
     */

    public function index() {


        $poname = I("get.POnameList", "");
        $POnameList = M('product_po')->field("po_name")->group("po_name")->select();
        $this->assign('POnameList', $POnameList);

        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $m = M('goods');
        $sh['keyword'] = I('get.keyword');
        $sh['sku'] = I('get.sku');
        $sh['goods_type_id'] = I('get.goods_type_id');
        $where = array();
        if ($sh['keyword'] && !empty($sh['keyword'])) {
            $where['g.name'] = array('like', "%{$sh['keyword']}%");
        }
        if ($sh['sku'] && !empty($sh['sku'])) {
            $where['earn13'] = array('eq', $sh['sku']);
        }
        if ($sh['goods_type_id'] && !empty($sh['goods_type_id'])) {
            $where['goods_type_id'] = array('eq', $sh['goods_type_id']);
        }
        if ($poname && !empty($poname)) {

            $suuklist = M("product_po")->field("sku")->where("po_name='$poname'")->select();
            foreach ($suuklist as $value) {
                $va[] = $value['sku'];
            }
            if ($va) {
                $where = array('sku' => array("in", $va));
            }
        }

        $pagesize = 20; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
        $count = $m->join('as g LEFT JOIN zt_goods_type as gt ON g.goods_type_id = gt.id')
                        ->join('LEFT JOIN zt_goods_brand as gb ON g.goods_brand_id = gb.id')
                        ->join('LEFT JOIN zt_partner as p ON g.own_shopid = p.id')
                        ->join('LEFT JOIN zt_country as c ON g.made_in = c.country_id')
                        ->where($where)->count();
        $list = $m->join('as g LEFT JOIN zt_goods_type as gt ON g.goods_type_id = gt.id')
                ->join('LEFT JOIN zt_goods_brand as gb ON g.goods_brand_id = gb.id')
                ->join('LEFT JOIN zt_partner as p ON g.own_shopid = p.id')
                ->join('LEFT JOIN zt_country as c ON g.made_in = c.country_id')
                ->where($where)->limit($offset . ',' . $pagesize)
                ->field('g.*,gt.name as type_name,gb.name as brand_name,p.name as partner_name,c.chinese_name,c.enabled as country_enabled')
                ->select();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();




        $partnerModel = D("Partner");
        $localstore = $partnerModel->getAvailableLocalStore("id,name");
        $customers = M("Customer")->field("id,shop_name")->select();

        //查看该商品是否已经添加至
        if ($list) {
            $opModel = M("Goods_op");
            foreach ($list as $key => $value) {
                $addnew = $opModel->field("goods_id,op,rsp,store_id,site_id")->where("goods_id={$value['id']} ")->select();
                $list[$key]['op'] = $addnew;
            }
        }
        $tree = new \Tree\Tree(M('goods_type')->field('id,pid,name')->select());
        $tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;|', '&nbsp;&nbsp;&nbsp;&nbsp;|------------', '&nbsp;&nbsp;&nbsp;&nbsp;|-');
        $this->assign('select_option_list', $tree->get_tree(0, '<option value=\$id \$selected>\$spacer\$name</option>'));
        $this->assign('customers', $customers);
        $this->assign('localstore', $localstore);
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('sh', $sh);
        $tradeList = D("Trade")->getTradList();
        $this->assign('tradeList', $tradeList);
        $this->assign('total', M('goods')->count() );
        $this->assign('supply_total', M('goods_supply')->join('JOIN zt_customer as c ON c.id = g.customer_id')->join('JOIN zt_goods as t ON t.id = g.goods_id')->alias('g')->where(array('g.status' => 2))->count());
        $this->display();
    }

    /*
     * 商品添加
     */

    public function add() {

        $goods_brand = M('Goods_brand')->field('id,name')->select();
        $goods_types = M('Goods_type')->field('id,name,pid')->select();
        $country = M('country')->where(array('enabled' => 'true'))->field('country_id,Chinese_name')->select();

        $tradeList = M("Trade")->group('code')->select();


        $tree = new \Tree\Tree(M('goods_type')->field('id,pid,name')->select());
        $tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;|', '&nbsp;&nbsp;&nbsp;&nbsp;|------------', '&nbsp;&nbsp;&nbsp;&nbsp;|-');

        $this->assign('select_option_list', $tree->get_tree(0, '<option value=\$id \$selected>\$spacer\$name</option>'));
        $this->assign('country', $country);
        $this->assign('goods_brand', $goods_brand);
        $this->assign('tradeList', $tradeList);

        $this->display('form');
    }

    public function update() {
        $m = M('goods');
        $id = I('post.id', '', 'intval');
        $data = I('post.arr');
        $pic_thumb = I('post.pic_thumb', '', 'strip_tags');

        $data['pic_thumb'] = $pic_thumb ? $pic_thumb : '';
        if ($data['info_keywords']) {
            $data['info_keywords'] = json_encode(array_unique(explode("、", $data['info_keywords'])));
        }

        if ($id) {
            $m->data($data)->where("id='{$id}'")->save();
            addlog('编辑商品，ID：' . $id);
        } else {
            $m->data($data)->add();
            addlog('新增商品，名称：' . $data['name']);
        }

        $this->success('操作成功！', U('index'));
    }

    /*
     * 商品编辑
     */

    public function edit($id = 0) {
        $id = intval($id);

        $m = M('goods');
        $goods = $m->where("id='$id'")->find();
        if (!$goods) {
            $this->error('参数错误！');
        }
        $goods['info_keywords'] = implode('、', json_decode($goods['info_keywords']));
        $goods_brand = M('Goods_brand')->field('id,name')->select();
        $goods_types = M('Goods_type')->field('id,name,pid')->select();
        $country = M('country')->where(array('enabled' => 'true'))->field('country_id,Chinese_name')->select();

        $tradeList = M("Trade")->group('code')->select();
        $tree = new \Tree\Tree(M('goods_type')->field('id,pid,name')->select());
        $tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;|', '&nbsp;&nbsp;&nbsp;&nbsp;|------------', '&nbsp;&nbsp;&nbsp;&nbsp;|-');
        $this->assign('select_option_list', $tree->get_tree(0, '<option value=\$id \$selected>\$spacer\$name</option>'));
        $this->assign('tradeList', $tradeList);
        $this->assign('goods_brand', $goods_brand);

        $this->assign('country', $country);
        $this->assign('goods', $goods);
        $this->display('form');
    }

    public function del() {
        $ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;

        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                $ids[$k] = intval($v);
            }
            if (!$ids) {
                $this->error('参数错误！');
                $uids = implode(',', $uids);
            }
        }

        $map['id'] = array('in', $ids);
        if (M('goods')->where($map)->delete()) {
            addlog('删除商品ID：' . $ids);
            $this->success('恭喜，商品删除成功！');
        } else {
            $this->error('参数错误！');
        }
    }

    /*
     * sku拉取商品信息
     */

    public function pull() {

        $sku = I('sku');
        $msg ['errno'] = 0;
        $msg ['msg'] = "拉取成功";

        if (M('goods')->where(array('sku' => $sku))->find()) {
            $msg ['errno'] = 1;
            $msg ['msg'] = "绑定失败，sku商品已经存在";
            $this->ajaxReturn($msg);
        }

        $odooerp = new OdooApiController();
        $odooerp->_initializeB();
        $data = $odooerp->readbySku($sku);
        if (!$data) {
            $msg ['errno'] = 2;
            $msg ['msg'] = "没有找到该商品";
            $this->ajaxReturn($msg);
        }
        $msg['data'] = $data;

        //$data[0]['qty_available']);

        $this->ajaxReturn($msg);
    }

    public function cpstart() {

        //显示批次号

        $poname = I("post.POnameList", "");
        $POnameList = M('product_po')->field("po_name")->group("po_name")->select();
        $this->assign('POnameList', $POnameList);
        /* 	$odooerp->url="http://erp.newbeemall.com:8069/";
          $odooerp->db="anxe_021";
          $odooerp->username="admin";
          $odooerp->password="oscg2015";
          $odooerp->_initialize();
          //$odooerp->readbySo();
         */
        //$odooerp->search();
        //$odooerp->search_read();
//        $po_name = 'PO00420';
        //echo "===".$_POST['po_name'].strpos($_POST['po_name'],'PO')."<br>";
        // echo "123>>>>".(stristr($_POST['po_name'],'PO')!=false)."<<<2123";
        if (stristr($_POST['po_name'], 'PO') != false) {
            $odooerp = new OdooApiController();
            $po_name = trim($_POST['po_name']);
            // echo "123>>>>".(strpos($_POST['po_name'],'PO')==0)."<<<123";
            // die();		 
            $dataline = $odooerp->readbySo($po_name);
            M('product_po')->where("PO_name='" . $po_name . "'")->delete();

            foreach ($dataline as $key => $val) {
                //	echo "<br>".$key."<br>";
                //echo "<br>".$val['product_id'][0].":".$val['product_id'][1]."<br>";
                //echo "<br> 参加价格:".$val['ref_price'].":供应商：".$val['partner_id'][0].$val['partner_id'][1]."<br>";
                //var_dump($val);die();

                $data['PO_name'] = $po_name;

                preg_match("/\[(.+)\](.+)/", $val['product_id'][1], $matches);
                //echo ">>>>";var_dump($matches);
                $data['sku'] = $matches[1];
                $data['product_id'] = $val['product_id'][0];
                $data['PO_name'] = $po_name;
                $data['ean13'] = $val['ean13'];
                $data['partner_id'] = $val['partner_id'][0];
                $data['partner_name'] = $val['partner_id'][1];
                $data['name'] = $matches[2];
                $data['ref_price'] = $val['ref_price'];
                $data['lst_price'] = $val['lst_price'];
                $data['local_price'] = $val['local_price'];
                $data['foreign_price'] = $val['foreign_price'];
                $data['market_price'] = $val['lst_price'];
                $data['price'] = floor(($val['lst_price'] + $val['price_unit']) / 2);
                $data['cost_price'] = $val['price_unit'];
                try {
                    if (strlen($po_name) > 6 && strpos($po_name, 'P') == 0)
                        M('product_po')->data($data)->add();
                } catch (\Exception $err) {
                    if (strpos($err->getMessage(), 'Duplicate entry') > 0) {
                        $errstr = "重复";
                    }
                }


                //var_dump($val);die();
            }
            $_GET['po_name'] = $po_name;
        }

        // echo ">>>".$_GET['po_name'];
//        $

        $_GET['po_name'] = $poname ? $poname : $_GET['po_name'];
        if ($_GET['po_name']) {
            /// 
            $where = " PO_name='" . $_GET['po_name'] . "'";
            //echo $where ;
            $list = M('product_po')->where($where)->select();

            // var_dump($list);
        } else {

            $page = I('get.p') ? I('get.p') : 1;

            $this->_row = 50;

            $list = M('product_po')->page($page, $this->_row)->select();
            $total = M('product_po')->where($where)->count();
            $this->__assignPage($total);
        }
        //处理关键字
        foreach ($list as $key => $lis) {
            $keywordtemp = implode("、", json_decode($lis['info_keywords'], 1));
            $list[$key]['info_keywords'] = $keywordtemp;
        }
//        print_r($list[0]);die;
        $this->assign('list', $list);

        //分配贸易模式列表

        $tradeList = D('Trade')->getTradList();
        $this->assign("tradelist", $tradeList);
        $Made_inList = D('Goods')->getMade_in_list();
        $this->assign("madeinlist", $Made_inList);
        $this->assign("goods_brand_idlist", D('goods_brand')->field("id,name")->order("convert(name using gbk) asc")->cache(600)->select());
        /*
          $openerp=new openerp();

          $openerp->connect();

          $opdata=array('display_name ilike "PO00"',);
          //$resp=$openerp->callX('purchase.order','search',$opdata);
          $resp=$openerp->callX('purchase.order','search',$opdata);
          var_dump($resp);
          die();
          //var_dump($odooerp);
         */

        $this->display('cpstart');
    }

    public function editBath() {
        $goodids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;
        $market_price = isset($_REQUEST['market_price']) ? $_REQUEST['market_price'] : false;
        $cost_price = isset($_REQUEST['cost_price']) ? $_REQUEST['cost_price'] : false;
        $goods_type = isset($_REQUEST['goods_type']) ? $_REQUEST['goods_type'] : false;
        $price = isset($_REQUEST['price']) ? $_REQUEST['price'] : false;

        //var_dump($market_price);

        $uid = $this->USER['uid'];

        $i = 0;

        foreach ($goodids as $key => $goods) {
            ///echo $goods."->".$market_price[$key]."->".$cost_price[$key]."->".$goods_type[$key]."<br>";
            if (isset($market_price[$key]) && $market_price[$key]) {
                $data['market_price'] = $market_price[$key];
            }
            if (isset($cost_price[$key]) && $cost_price[$key]) {
                $data['cost_price'] = $cost_price[$key];
            }

            if (isset($goods_type[$key]) && $goods_type[$key]) {
                $data['goods_type_id'] = $goods_type[$key];
            }
            if (isset($price[$key]) && $price[$key]) {
                $data['price'] = $price[$key];
            }
            if (isset($_POST['goods_type_id'][$key]) && $_POST['goods_type_id'][$key]) {
                $data['goods_type_id'] = $_POST['goods_type_id'][$key];
            }
            if (isset($_POST['made_in'][$key]) && $_POST['made_in'][$key]) {
                $data['made_in'] = $_POST['made_in'][$key];
            }
            if (isset($_POST['tax_no'][$key]) && $_POST['tax_no'][$key]) {
                $data['tax_no'] = $_POST['tax_no'][$key];
            }
            if (isset($_POST['tax_xf'][$key]) && $_POST['tax_xf'][$key]) {
                $data['tax_xf'] = $_POST['tax_xf'][$key];
            }
            if (isset($_POST['tax_gw'][$key]) && $_POST['tax_gw'][$key]) {
                $data['tax_gw'] = $_POST['tax_gw'][$key];
            }
            if (isset($_POST['tax_add'][$key]) && $_POST['tax_add'][$key]) {
                $data['tax_add'] = $_POST['tax_add'][$key];
            }
            if (isset($_POST['info_keywords'][$key]) && $_POST['info_keywords'][$key]) {
                $data['info_keywords'] = json_encode(explode("、", $_POST['info_keywords'][$key]));
            }
            if (isset($_POST['trade_type'][$key]) && $_POST['trade_type'][$key]) {
                $data['trade_type'] = $_POST['trade_type'][$key];
            }
            if (isset($_POST['stock'][$key]) && $_POST['stock'][$key]) {
                $data['stock'] = $_POST['stock'][$key];
            }
            if (isset($_POST['pom'][$key]) && $_POST['pom'][$key]) {
                $data['pom'] = $_POST['pom'][$key];
            }
            if (isset($_POST['exp_time'][$key]) && $_POST['exp_time'][$key]) {
                $data['exp_time'] = $_POST['exp_time'][$key];
            }
            if (isset($_POST['goods_brand_id'][$key]) && $_POST['goods_brand_id'][$key]) {
                $data['goods_brand_id'] = $_POST['goods_brand_id'][$key];
            }
            if (isset($goods) && $goods) {
                $data['id'] = $goods;
            }
            $data['uid'] = $uid;
            $data['mdate'] = time();
            $data['stat'] = ($market_price[$key] > 0 && $cost_price[$key] > 0 && $goods_type[$key] > 0 && $price[$key] > 0) ? 1 : 0;
            if (!$goods) {
                continue;
            }
            M('product_po')->where(array('id' => $goods))->save($data);
            $this->ptogoods($goods);
            $i = $i + 1;
        }

        $this->success('操作成功！' . $i);
    }

    public function ptogoods($po_id = 1) {
        //echo $po_id;
        $po = M('product_po')->where('id=' . $po_id)->find();
        //echo $po['sku'];
        $goods = M('goods')->where(array("sku" => $po['sku']))->find();
        //if(!$goods&&$po['sku']=='') $goods = M('goods')->where(array("name"=>$po['name']))->find();


        if (isset($po['name']) && $po['name']) {
            $data['name'] = $po['name'];
        }
        if (isset($po['sku']) && $po['sku']) {
            $data['sku'] = $po['sku'];
        }
        if (isset($po['goods_type_id']) && $po['goods_type_id']) {
            $data['goods_type_id'] = $po['goods_type_id'];
        }
        if (isset($po['market_price']) && $po['market_price']) {
            $data['price_market'] = $po['market_price'];
        }
        if (isset($po['cost_price']) && $po['cost_price']) {
            $data['price_cost'] = $po['cost_price'];
        }
        if (isset($po['price']) && $po['price']) {
            $data['price'] = $po['price'];
        }
        if (isset($po['stock']) && ($po['stock'] || $po['stock'] == 0)) {
            $data['stock_num'] = $po['stock'];
        }
        if (isset($po['exp_time']) && $po['exp_time']) {
            $data['die_time'] = $po['exp_time'];
        }
        if (isset($po['ean13']) && $po['ean13']) {
            $data['earn13'] = $po['ean13'];
        }


        if (isset($po['pom']) && $po['pom']) {
            $data['pom'] = $po['pom'];
        }
        if (isset($po['weight']) && $po['weight']) {
            $data['weight'] = $po['weight'];
        }
        if (isset($po['made_in']) && $po['made_in']) {
            $data['made_in'] = $po['made_in'];
        }
        if (isset($po['tax_no']) && $po['tax_no']) {
            $data['tax_no'] = $po['tax_no'];
        }
        if (isset($po['tax_xf']) && $po['tax_xf']) {
            $data['tax_xf'] = $po['tax_xf'];
        }
        if (isset($po['tax_gw']) && $po['tax_gw']) {
            $data['tax_gw'] = $po['tax_gw'];
        }
        if (isset($po['tax_add']) && $po['tax_add']) {
            $data['tax_added'] = $po['tax_add'];
        }
        if (isset($po['extra_info']) && $po['extra_info']) {
            $data['extra_info'] = $po['extra_info'];
        }
        if (isset($po['goods_brand_id']) && $po['goods_brand_id']) {
            $data['goods_brand_id'] = $po['goods_brand_id'];
        }
        if (isset($po['info_keywords']) && $po['info_keywords']) {
            $data['info_keywords'] = $po['info_keywords'];
        }
        if (isset($po['trade_type']) && $po['trade_type']) {
            $data['trade_type'] = $po['trade_type'];
        }

        if (!$goods || strlen($po['sku']) == 0) {
            M('goods')->add($data);
        } else {

            M('goods')->where(array("sku" => $po['sku']))->data($data)->save();
        }
    }

    /*
     * 商品的批处理相关
     */

    function goodsBath() {
        $ids = I("post.ids");
        $siteids = I("post.siteids");
        $storeids = I("post.storeids", 0);
        $optype = I("post.optype", ADD_NEW);
//        var_dump($optype);die;
        $jumpUrl = $_SERVER['HTTP_REFERER'];
        if (empty($ids) || !$ids) {
            $this->error("商品为空，请选择要操作的商品");
        }
        if (empty($siteids) || !$siteids) {
            $this->error("站点为空，请选择要操作的站点");
        }
//        if (empty($storeids) || !$storeids) {
//            $this->error("店铺为空，请选择要操作的店铺");
//        }

        $data = array();
        foreach ($ids as $key => $goods_id) {
            foreach ($siteids as $sk => $svalue) {
                $tempdata['goods_id'] = $goods_id;
                $tempdata['site_id'] = $svalue;
                $tempdata['op'] = $optype;
                $tempdata['uid'] = $this->USER['uid'];
                $tempdata['store_id'] = $storeids;
                $tempdata['optime'] = time();
                $data[] = $tempdata;
            }
        }
//        var_dump($data);die;
        $opModel = M("Goods_op");
        $opModel->startTrans();
        foreach ($data as $goodsdata) {
            $where['goods_id'] = $goodsdata['goods_id'];
            $where['site_id'] = $goodsdata['site_id'];
            $where['op'] = $goodsdata['op'];
//            $where['store_id'] = $goodsdata['store_id'];
            $hasid = $opModel->where($where)->getField("id");
            if ($hasid) {
                $updata = $goodsdata;
                $updata['rsp'] = '';
                $flag = $opModel->where(array("id" => $hasid))->save($updata);
            } else {
                $flag = $opModel->add($goodsdata);
            }

            if (!$flag) {
                $opModel->rollback();
                $this->error("操作失败，请重试", $jumpUrl);
            }
        }
        $opModel->commit();
        $this->success("操作成功", $jumpUrl);
    }

    /**
     * *商品检查
     */
    function goodscheck() {
        $GoodsModel = D("Goods");
        $GoodsModel->checkgoodsaddnew();
        $this->success("检查成功", U("Index/index"));
    }

    /**
     * EXECL导入数据
     * 功能主要入库产品库，有导入日志记录，过滤重复数据记录等功能
     * @author wyb
     */
    public function exportGoodsExecl() {
        set_time_limit(0);
        header("Content-type:text/html;charset=utf-8");
        if ($_FILES["execl_goods"]["error"] > 0) {
            exit('<script>parent.title = "Error：' . $_FILES["file"]["error"] . '";parent.code = "error";parent.tips_msg()</script>');
        }
        if (!$_FILES['execl_goods']['name']) {
            exit('<script>parent.title = "请选择需要导入的商品execl文件！";parent.code = "error";parent.tips_msg()</script>');
        }
        //添加导入日志
        $export_id = M('product_export_log')->add(array('admin_id' => $this->USER['uid'], 'upload_file_name' => $_FILES['execl_goods']['name'], 'upload_time' => time()));
        $ext = pathinfo($_FILES['execl_goods']['name'], PATHINFO_EXTENSION);
        if (!in_array($ext, array('xls', 'xlsx'))) {
            exit('<script>parent.title = "上传文件格式错误，必须是execl！";parent.code = "error";parent.tips_msg()</script>');
        }
        $upload_path = SITE_FILE . '/Uploads/';
        if (!file_exists($upload_path))
            mkdir($upload_path);
        $file_name = time() . rand(1000, 9999) . '.' . $ext;
        $filePath = $upload_path . $file_name;
        if (!move_uploaded_file($_FILES['execl_goods']['tmp_name'], $filePath)) {
            exit('<script>parent.title = "文件上传失败，请重新上传！";parent.code = "error";parent.tips_msg()</script>');
        }
        //上传成功之后日志记录
        M('product_export_log')->where(array('id' => $export_id))->save(array('upload_over_time' => time(), 'export_file' => 'Uploads/' . $file_name, 'upload_max' => filesize($filePath)));

        import("Org.Util.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        import("Org.Util.PHPExcel.Reader.Excel2007");
        $PHPReader = new \PHPExcel_Reader_Excel2007(); //默认是excel2007
        //判断读取是否成功不成功则实例化2005的
        if (!$PHPReader->canRead($filePath)) {
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader = new \PHPExcel_Reader_Excel5(); //如果不成功的时候用以前的版本来读取  
            if (!$PHPReader->canRead($filePath)) {
                exit('<script>parent.title = "请选择需要导入的商品execl文件!";parent.code = "error";parent.tips_msg()</script>');
                return;
            }
        }
        //加载数据
        $PHPExcel = $PHPReader->load($filePath);
        //默认第一张表的数据
        $currentSheet = $PHPExcel->getSheet(0);
        //取得一共有多少列  
        $allColumn = $currentSheet->getHighestColumn();
        //取得一共有多少行  
        $allRow = $currentSheet->getHighestRow();
        //判断数据的条数
        if ($allRow <= 1) {
            exit('<script>parent.title = "上传的execl无数据，或者已损坏！";parent.code = "error";parent.tips_msg()</script>');
        }
        $fields = array('A' => 'PO_name', 'B' => 'ean13', 'C' => 'sku', 'F' => 'name', 'J' => 'pom', 'O' => 'stock', 'Q' => 'cost_price', 'S' => 'price', 'R' => 'ref_price', 'R' => 'market_price');
        $excelfield = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
        $excelfld = explode(',', $excelfield);

        $num = array(); //成功条数
        $error_num = array(); //错误条数
        $repeat_num = array(); //重复条数
        //循环读取数据,默认是utf-8输出
        $model = M('product_po');


        for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
            //echo $currentRow."<br>";
            if ($currentRow <= 1)
                continue;
            $add_data = array();
            /*
              for($currentColumn='A';$currentColumn<='Z';$currentColumn++) {
              //设置的字段获取数据组装

              if( isset( $fields[ $v ] ) ) $add_data[$fields[$currentColumn]] = $PHPExcel->getActiveSheet()->getCell($currentColumn.$currentRow)->getValue();


              }
             */

            foreach ($excelfld as $v) {
                if (isset($fields[$v]))
                    $add_data[$fields[$v]] = $PHPExcel->getActiveSheet()->getCell($v . $currentRow)->getValue();
            }

            //var_dump($add_data);
            //echo "<br>";
            //查询sku是否重复
            if ($add_data['sku'] && $model->where(array('sku' => $add_data['sku']))->find()) {
                $repeat_num[] = $add_data['sku']; //记录重复的SKU
                unset($add_data[$currentRow]);
            } else {

                if ($model->add($add_data) === false) {
                    $error_num[] = $add_data['sku'];
                } else {
                    $num[] = $add_data['sku'];
                }
            }
        }
        //导入成功之后日志记录
        M('product_export_log')->where(array('id' => $export_id))->save(array('export_over_time' => time(), 'content' => serialize(array("success" => implode(',', $num), "repeat" => implode(',', $repeat_num), "error" => implode(',', $error_num)))));
        exit('<script>parent.title = "<div style=\"margin:0px auto;text-align:left; width:200px;\">成功导入：【' . count($num) . '】条数据<br>重复导入：【' . count($repeat_num) . '】条数据<br>导入错误：【' . count($error_num) . '】条数据<br>详情请查看<a href=\"' . U('Goods/goodsExporLogtList') . '\">商品导入日志</a></span>";parent.code = "success";parent.tips_msg()</script>');
    }

    /**
     * 商品导入日志列表
     * 展示列表，可展示成功，重复，失败导入的商品sku
     * @author wyb
     */
    public function goodsExporLogtList() {
        $where = array();
        $page = I('get.p') ? I('get.p') : 1;
        if (I('get.admin_id')) {
            $where['admin_id'] = I('get.admin_id');
        }
        if (I('get.sku')) {
            $where['content'] = array('like', "%" . I('get.sku') . "%");
        }
        $model = M('product_export_log');
        $data = $model->alias('p')->join('__MEMBER__ a ON p.admin_id = a.uid')->field('p.*,a.user')->where($where)->page($page, $this->_row)->order('id DESC')->select();
        $total = $model->where($where)->count();
        $this->__assignPage($total);
        foreach ($data as $key => $value) {
            $data[$key]['content'] = unserialize($value['content']);
        }
        $this->assign('lists', $data);
        $this->assign('member_list', M('member')->field('uid,user')->select());
        $this->display();
    }

    function insertBrand() {
        $data = json_decode(file_get_contents("./brands.txt"), 1);
        $insertda = array();
        foreach ($data as $vv) {
            $temp['id'] = $vv['brand_id'];
            $temp['name'] = $vv['brand_chinese_name'] ? $vv['brand_chinese_name'] : $vv['brand_name'];
            $temp['info'] = $vv['brand_desc'];
            $insertda[] = $temp;
        }

        $mode = M("Goods_brand");
        foreach ($insertda as $key => $value) {
            $mode->add($value);
//            echo $mode->_sql();
        }
    }

    function geterrorGoods() {
        $M = M("goods_op");
        $map = array(
//            'goods_id'
            "rsp" => 'error',
            "site_id" => '10001',
        );
        $list = $M->table("__GOODS_OP__ as go")->where($map)->join('__GOODS__  as g on g.id=goods_id', "left")->field("go.log,g.name")->select();
        echo $M->_sql();
        var_dump($list);
    }

    function bind_types_test() {
        $type_model = M("goods_type");
        $shop_type_model = M("shop_types");
        $localList = $type_model->select();

        foreach ($localList as $key => $value) {
            $where['name'] = $value['name'];
            $where['shop_sites_id'] = '10002';
            $count = $shop_type_model->where($where)->count();
            if ($count > 1) {
                echo "{$value['id']}:{$value['name']},";
                continue;
            }
            $data['goods_type_id'] = $value['id'];
//            $data['goods_type_id']=null;
            $shop_type_model->where($where)->save($data);
        }
    }

    function trimtype_id() {
        $data = array();

        $model = M("Goods");
        $modelshop = M("shop_types");


        $noneedids = $model->where('sku in ("P0111147","P0111151","P0111153","P0111154","P0111156","P0111161","P0111164","P0111170","P0111183","P0111190","P0111194","P0111197","P0111199","P0111201","P0111203","P0111205","P0111208","P0111210","P0111213","P0111216","P0111220","P0111222","P0111226","P0111229")')->field("id,goods_type_id")->select();
        $neenoneed = array();
//        file_put_contents("./noneeddata.txt",  var_export($noneedids,true));
        foreach ($noneedids as $aa) {
            $neenoneed[] = $aa['id'];
        }


        $data = $model->field("id,goods_type_id")->select();
        foreach ($data as $d) {
            if (in_array($d['id'], $neenoneed)) {
                echo $d['id'] . "<br>";
                continue;
            }
            $where['shop_type_id'] = $d['goods_type_id'];
            $where['shop_sites_id'] = 10001;

            $res = $modelshop->where($where)->find();




//          $up['goods_type_id']=intval($d['goods_type_id'])%1000000000;
//          $model->where("id={$d['id']}")->save($up);
        }
    }

    /**
     * 批量从excel 中导入要批量操作的数据
     * 更新商品表 同事根据操作类型写入OP 表
     */
    function excelbath() {
        if ($_POST) {
            $ponum = I('post.ponum', '');
            if (!$ponum) {
                $this->error("批次号不能为空");
            }

            //处理
            //处理文件   读取数据  写入数据   删除文件
            set_time_limit(0);
            $op = I("post.optionsOP", "");
            header("Content-type:text/html;charset=utf-8");
            if ($_FILES["files"]["error"] > 0) {
                exit('<script>parent.title = "Error：' . $_FILES["files"]["error"] . '";parent.code = "error";parent.tips_msg()</script>');
            }
            if (!$_FILES['files']['name']) {
                exit('<script>parent.title = "请选择需要导入的商品execl文件！";parent.code = "error";parent.tips_msg()</script>');
            }
            $ext = pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
            if (!in_array($ext, array('xls', 'xlsx'))) {
                exit('<script>parent.title = "上传文件格式错误，必须是execl！";parent.code = "error";parent.tips_msg()</script>');
            }
            $upload_path = SITE_FILE . './Public/batchexcel/';
            if (!file_exists($upload_path))
                mkdir($upload_path);
            $file_name = time() . rand(1000, 9999) . '.' . $ext;
            $filePath = $upload_path . $file_name;
            if (!move_uploaded_file($_FILES['files']['tmp_name'], $filePath)) {
                exit('<script>parent.title = "文件上传失败，请重新上传！";parent.code = "error";parent.tips_msg()</script>');
            }


            import("Org.Util.PHPExcel");
            $objPHPExcel = new \PHPExcel();
            import("Org.Util.PHPExcel.PHPExcel.IOFactory");
//echo PHPExcel_Shared_Date::ExcelToPHP($data['2'][A]);
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader = new \PHPExcel_Reader_Excel2007(); //默认是excel2007
            //判断读取是否成功不成功则实例化2005的
            if (!$PHPReader->canRead($filePath)) {
                import("Org.Util.PHPExcel.Reader.Excel5");
                $PHPReader = new \PHPExcel_Reader_Excel5(); //如果不成功的时候用以前的版本来读取  
                if (!$PHPReader->canRead($filePath)) {
                    exit('<script>parent.title = "请选择需要导入的商品execl文件!";parent.code = "error";parent.tips_msg()</script>');
                    return;
                }
            }
            //加载数据
            $PHPExcel = $PHPReader->load($filePath);
            //默认第一张表的数据
            $currentSheet = $PHPExcel->getSheet(0);
            //取得一共有多少列  
            $allColumn = $currentSheet->getHighestColumn();
            //取得一共有多少行  
            $allRow = $currentSheet->getHighestRow();
            //判断数据的条数
            if ($allRow <= 1) {
                exit('<script>parent.title = "上传的execl无数据，或者已损坏！";parent.code = "error";parent.tips_msg()</script>');
            }
            $fields = array('A' => 'sku', 'B' => 'name', 'C' => 'pom', 'D' => 'stock_num', 'E' => 'price', 'F' => 'die_time');
            $excelfield = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
            $excelfld = explode(',', $excelfield);

            $num = array(); //成功条数
            $error_num = array(); //错误条数
            $repeat_num = array(); //重复条数
            //循环读取数据,默认是utf-8输出
            $gmodel = M('Goods');
            $opModel = M("Goods_op");
            $SiteModel = M("Customer");
            $sitelist = $SiteModel->field("id")->select();

            for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
                echo $currentRow . "<br>";
                if ($currentRow <= 1)
                    continue;
                $add_data = array();
                /*
                  for($currentColumn='A';$currentColumn<='Z';$currentColumn++) {
                  //设置的字段获取数据组装

                  if( isset( $fields[ $v ] ) ) $add_data[$fields[$currentColumn]] = $PHPExcel->getActiveSheet()->getCell($currentColumn.$currentRow)->getValue();


                  }
                 */

                foreach ($excelfld as $v) {
                    if (isset($fields[$v])) {
                        $add_data[$fields[$v]] = $PHPExcel->getActiveSheet()->getCell($v . $currentRow)->getValue();
                    }
                }

                $sku = $add_data['sku'];
                if (!$sku) {
                    continue;
                }
                if ($add_data['die_time']) {
                    $add_data["die_time"] = date("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($add_data["die_time"]));
                }
                //更新 商品
                $data = array();
                if (isset($add_data['die_time'])) {
                    $data['die_time'] = $add_data['die_time'];
                }
//                if(isset($add_data['name'])){
//                    $data['name']=$add_data['name'];
//                }
                if (isset($add_data['price']) && $op == UPDATE_GOODS_PRICE) {
                    $data['price'] = $add_data['price'];
                }
                if (isset($add_data['stock_num']) && $op == UPDATE_GOODS_STOCE) {
                    $data['stock_num'] = $add_data['stock_num'];
                }

                //获取goods_id
                $goods_id = $gmodel->where(array("sku" => $sku))->getField("id");
                if (!$goods_id) {
                    echo "货号{$sku} 在商品中没找到 已经跳过<br>";
                    continue;
                }
                //如果是上下架  就跳过更新商品  
                if (!in_array($op, array(GOODS_DOWN, GOODS_ONLINE))) {
                    $gmodel->where(array("id" => $goods_id))->save($data);
                }

                //添加OP表
//                $data = array();
//                $where = array();
//                $where['goods_id'] = $goods_id;
//                $where['op'] = $op;
//                foreach ($sitelist as $site) {
//                    $where['site_id'] = $site['id'];
//                    $data['site_id'] = $site['id'];
//                    $data['goods_id'] = $goods_id;
//                    $data['op'] = $op;
//                    $data['optime'] = time();
//                    $data['uid'] = $this->USER['uid'];
//                    $data['rsp'] = '';
//
//                    $hasid = $opModel->where($where)->getField("id");
//                    if ($hasid) {
//                        $flag = $opModel->where(array("id" => $hasid))->save($data);
//                    } else {
//                        $flag = $opModel->add($data);
//                    }
//                }
                //添加批次处理
            }
            @unlink($filePath);
            echo "处理完毕<a traget='new' href='/index.php'>回首页</a>";
        } else {
            $this->display();
        }
    }

    function tempgoods_stock() {
        die;
        $sql = 'select id as goods_id from zt_goods where sku in ("P0042136","P0042124","P0042097","P0042592","P0042596","P0041831","P0041832","P0041833","P0043672","P0043673","P0043674","P0043675","P0043676","P0043677","P0043678","P0043679","P0043680","P0043681","P0043028","P0043076","P0043077","P0043079","P0043081","P0043082","P0043083","P0043084","P0043085","P0043090","P0043092","P0051919","P0051920","P0051921","P0051922","P0051923","P0051925","P0051926","P0051927","P0051928","P0051933","P0051934","P0051935","P0051954","P0043169","P0043218","P0043232","P0043233","P0052015","P0065163","P0065178","P0065182","P0065183","P0065185","P0065188","P0065189","P0065204","P0065206","P0042217","P0042218","P0042219","P0042220","P0042221","P0042222","P0042226","P0042228","P0001653","P0001654","P0001655","P0001656","P0001676","P0001679","P0001721","P0001743","P0042261","P0042260","P0042471","P0042950","P0042225","P0042227","P0001650","P0001668","P0001673","P0001675","P0001680","P0001716","P0067304","P0067306","P0049427","P0049428","P0109891","P0109892","P0043480","P0043481","P0109530","P0109893","P0109894","P0109572","P0109573","P0109574")';
        $goods_model = M("goods");
        $goods = $goods_model->field("id")->where('sku in ("P0042136","P0042124","P0042097","P0042592","P0042596","P0041831","P0041832","P0041833","P0043672","P0043673","P0043674","P0043675","P0043676","P0043677","P0043678","P0043679","P0043680","P0043681","P0043028","P0043076","P0043077","P0043079","P0043081","P0043082","P0043083","P0043084","P0043085","P0043090","P0043092","P0051919","P0051920","P0051921","P0051922","P0051923","P0051925","P0051926","P0051927","P0051928","P0051933","P0051934","P0051935","P0051954","P0043169","P0043218","P0043232","P0043233","P0052015","P0065163","P0065178","P0065182","P0065183","P0065185","P0065188","P0065189","P0065204","P0065206","P0042217","P0042218","P0042219","P0042220","P0042221","P0042222","P0042226","P0042228","P0001653","P0001654","P0001655","P0001656","P0001676","P0001679","P0001721","P0001743","P0042261","P0042260","P0042471","P0042950","P0042225","P0042227","P0001650","P0001668","P0001673","P0001675","P0001680","P0001716","P0067304","P0067306","P0049427","P0049428","P0109891","P0109892","P0043480","P0043481","P0109530","P0109893","P0109894","P0109572","P0109573","P0109574")')
                ->select();

        $data = array();
        $siteids = array('10001', '10003');
        foreach ($goods as $g) {

            foreach ($siteids as $sk => $svalue) {
                $tempdata['goods_id'] = $g['id'];
                $tempdata['site_id'] = $svalue;
                $tempdata['op'] = UPDATE_GOODS_STOCE;
                $tempdata['uid'] = $this->USER['uid'];
                $tempdata['store_id'] = 0;
                $tempdata['optime'] = time();
                $data[] = $tempdata;
            }
        }
        $opModel = M("Goods_op");
        $opModel->startTrans();
        foreach ($data as $goodsdata) {
            $where['goods_id'] = $goodsdata['goods_id'];
            $where['site_id'] = $goodsdata['site_id'];
            $where['op'] = $goodsdata['op'];
//            $where['store_id'] = $goodsdata['store_id'];
            $hasid = $opModel->where($where)->getField("id");
            if ($hasid) {
                $updata = $goodsdata;
                $updata['rsp'] = '';
                $flag = $opModel->where(array("id" => $hasid))->save($updata);
            } else {
                $flag = $opModel->add($goodsdata);
            }

            if (!$flag) {
                $opModel->rollback();
                $this->error("操作失败，请重试");
            }
        }
        $opModel->commit();
        echo "成功succ";
    }

}
